package com.liuyang.second.concurrency.chapter6;

public class SharedData {

    private final char[] buffer;
    private final ReadWriteLock lock = new ReadWriteLock();
    public SharedData(int size){
        this.buffer =new char[size];

        for(int i=0; i<size;i++){
            this.buffer[i] = '*';
        }
    }

    protected char[] read(){
        try {
            lock.readLock();
            return doRead();
        }finally {
            lock.readUnlock();
        }
    }
    public char[] doRead(){
        char[] newBuf = new char[buffer.length];
        for(int i=0; i<buffer.length;i++){
            newBuf[i] = buffer[i];
        }
        slowly(50);
        return newBuf;
    }

    private void slowly(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    protected void write(char c){
        try {
            lock.writeLock();
            this.doWrite(c);
        }finally {
            lock.writeUnlock();
        }
    }

    private void doWrite(char c) {
        for(int i=0; i<buffer.length;i++){
            buffer[i] = c;
            slowly(10);
        }
    }

}
